<?php
class GD {
    protected static function _generatorPNG($str) {
        $width = 50;
        $height = 20;
        $image = imagecreate($width, $height);
        if (empty($image)) {
            return false;
        }
        $bgColor = imagecolorallocate($image, 236, 247, 249);
        $textColor = imagecolorallocate($image, 0, 0, 0);
        
        imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgColor);
        imagerectangle($image, 0, 0, $width - 1, $height - 1, $textColor);
        imagestring($image, 23, 2, 2, $str, $textColor);
        
        for ($i = 0; $i < 25; $i++) {
            $randColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imagesetpixel($image, rand(0, 1000) % $width, rand(0, 1000) % $height, $randColor);
        }
        
        ob_start();
        imagepng($image);
        $png = ob_get_contents();
        ob_end_clean();
        imagedestroy($image);
        
        return $png;
    }
    
    public static function randStr() {
        $arr = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                     'K', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
                     'V', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
                     'g', 'k', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 
                     'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z',
                     'K', 'L'
        );
        
        return $arr[rand(0, 51)].$arr[rand(0, 51)].$arr[rand(0, 51)].$arr[rand(0, 51)].$arr[rand(0, 51)];
    }
    
    public static function getPNG($uid, $ip, $str) {    
    	$mc = new MCache();
    	$mc->set(self::gK($uid, $ip), $str, 0);
    	return self::_generatorPNG($str);    
    }
    
    public static function validate($uid, $ip, $vCode) {
        $mc = new MCache();
        $key = self::gK($uid, $ip);
        $code = $mc->get($key);
        if (!empty($code) && strtolower($vCode) == strtolower($code)) {
            return $mc->delete($key);
        }
        return false;
    }
    
    public static function gK($uid, $ip) {
        return md5("verify_".$uid."_".$ip);
    }
}
